﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AgnisEbmtTranslator;
using System.Threading;

namespace SubmissionTest
{
    // delegates used to call MainForm functions from worker thread
    public delegate void DelegateRefreshStatus(Object[] objs);
    public delegate void DelegateThreadFinished();

    public partial class FormTranslationTest : Form
    {
        // Translator Thread declaration
        Thread myTranslatorThread;

        // events used to stop worker thread
        ManualResetEvent m_EventStopThread;
        ManualResetEvent m_EventThreadStopped;

        // Delegate instances used to call user interface functions 
        // from worker thread:
        public DelegateRefreshStatus  m_DelegateRefreshStatus;
        public DelegateThreadFinished m_DelegateThreadFinished;

        private int nTransplants=1;

        private String currentEbmtDbConnectionString;
        private String currentMappingInfoConnectionString;
        private String currentAgnisStagingConnectionString;


        public void SetCurrentEbmtDbConnectionString (String cString)
        {
            currentEbmtDbConnectionString = cString;
        }

        public void SetCurrentMappingInfoConnectionString(String cString)
        {
            currentMappingInfoConnectionString = cString;
        }

        public void SetCurrentAgnisStagingConnectionString(String cString)
        {
            currentAgnisStagingConnectionString = cString;
        }

        public FormTranslationTest()
        {
            InitializeComponent();

            // initialize delegates
            m_DelegateRefreshStatus = new DelegateRefreshStatus(this.RefreshStatus);
            m_DelegateThreadFinished = new DelegateThreadFinished(this.ThreadFinished);

            // initialize events
            m_EventStopThread = new ManualResetEvent(false);
            m_EventThreadStopped = new ManualResetEvent(false);


        }

        DateTime t1;
        TimeSpan  t2;
        // Called from worker thread using delegate and Control.Invoke
        public void RefreshStatus(Object[] obj)
        {
            if ((bool)obj[3] == true)
            {
                txtProgress.Text = txtProgress.Text + "Processing ID:" + obj[0].ToString() + ", IDAA:" + obj[1].ToString() + ", date of transplant:" + obj[2].ToString()+ "\r\n";
                t1 = DateTime.Now;
                progressBar1.PerformStep();
            }
            else 
            {
                t2 = DateTime.Now -t1;
                txtProgress.Text = txtProgress.Text + "Process finished. Process executing time:\r\n" 
                    + t2.TotalSeconds + " seconds. \r\n";
            }
            txtProgress.SelectionStart = txtProgress.Text.Length - 1;
            txtProgress.ScrollToCaret();
        }

        // Called from worker thread using delegate and Control.Invoke
        public void ThreadFinished()
        {
            this.btnEbmtAgnisTranslation.Enabled = true;
            chkSendToDataBase.Enabled = true;
            MessageBox.Show ("Done.");
        }

   
        private void FormTranslationTest_Load(object sender, EventArgs e)
        {

            SqlConnection myTestConnection = new SqlConnection(currentEbmtDbConnectionString);
            this.aA_TableAdapter.Fill(this.ebmtDataSet.AA_ );
            progressBar1.Maximum = nTransplants;
            progressBar1.Step = 1;
        }


        
        private void btnEbmtAgnisTranslation_Click(object sender, EventArgs e)
        {
            btnEbmtAgnisTranslation.Enabled = false;
            chkSendToDataBase.Enabled = false;
            // Instantating the translation thread, we specify into the ThreadStart delegate
            // the name of the method that will be executed when we call Start() thread.
            MyTranslatorThreadHandle tHandle = new MyTranslatorThreadHandle(this.aA_BindingSource, this, m_EventStopThread, m_EventThreadStopped);
            tHandle.SetCurrentEbmtDbConnectionString(currentEbmtDbConnectionString);
            tHandle.SetCurrentMappingInfoConnectionString(currentMappingInfoConnectionString);
            tHandle.SetCurrentAgnisStagingConnectionString(currentAgnisStagingConnectionString);
            tHandle.StoreToDataBase = this.chkSendToDataBase.Checked;
            tHandle.NumberOfTransplantsToProcess = nTransplants;
            if (nTransplants == 1) tHandle.SelectedIndex = this.aA_BindingSource.IndexOf(this.aA_BindingSource.Current);
            progressBar1.Maximum = nTransplants;
            myTranslatorThread = new Thread(new ThreadStart(tHandle.ExecuteTranslationProcess));

            myTranslatorThread.Start();

        }

        // Stop worker thread if it is running.
        // Called when user presses Stop button or form is closed.
        private void StopTranslatorThread()
        {
            if (myTranslatorThread != null && myTranslatorThread.IsAlive)  // thread is active
            {
                // set event "Stop"
                m_EventStopThread.Set();

                // wait when thread  will stop or finish
                while (myTranslatorThread.IsAlive)
                {
                    // We cannot use here infinite wait because our thread
                    // makes syncronous calls to main form, this will cause deadlock.
                    // Instead of this we wait for event some appropriate time
                    // (and by the way give time to worker thread) and
                    // process events. These events may contain Invoke calls.
                    if (WaitHandle.WaitAll(
                        (new ManualResetEvent[] { m_EventThreadStopped }),
                        100,
                        true))
                    {
                        break;
                    }

                    Application.DoEvents();
                }
            }
        }

        private void FormTranslationTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopTranslatorThread();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex > -1)
            {
                if (!int.TryParse(comboBox1.SelectedItem.ToString(),out nTransplants))
                {
                    nTransplants = 1;
                }
            }
            else 
            {
                nTransplants = 1;
            }
          
        }

    }
}
